package ystp.support;


import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
public class CheckCode {
	  private static final long serialVersionUID = 1L;
	  public static final int WIDTH = 120;
	  public static final int HEIGHT = 40;
	  
	  @RequestMapping({"main/checkcode"})
	  public void getCheckCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		    BufferedImage image = new BufferedImage(120, 40, 1);
		    
		    Graphics g = image.getGraphics();
		    
		    getBackgroundColor(g);


		    
		    drawLine(g);
		    
		    drawNum(g, request);
		    
		    response.setContentType("image/jpeg");
		    
		    response.setDateHeader("expires", -1L);
		    response.setHeader("Pragma", "no-cache");
		    ImageIO.write(image, "jpg", (OutputStream)response.getOutputStream());
	  }
	  
	  private void drawNum(Graphics g, HttpServletRequest request) {
		    g.setColor(Color.RED);
		    g.setFont(new Font("SimSun", 1, 22));
		    String chs = "123456789";
		    int y = 10;
		    String sb = "";

		    
		    for (int x = 0; x < 4; x++) {
		      String ch = chs.charAt((new Random()).nextInt(chs.length())) + "";
		      g.drawString(ch, y, 25);
		      y += 25;
		      sb = sb + ch.toString();
		    } 

		    
		   // String sessionName = request.getParameter("name");
		  //  if (sessionName == null || "".equals(sessionName)) {
		  //    sessionName = "checkcode";
		 //   }
		    
		    HttpSession session = request.getSession();
		    session.setAttribute("checkcode", sb);
	  }
	  
	  private void drawLine(Graphics g) {
		    g.setColor(Color.BLUE);
		    for (int i = 0; i < 4; i++) {
		      int x1 = (new Random()).nextInt(120);
		      int y1 = (new Random()).nextInt(40);
		      int x2 = (new Random()).nextInt(120);
		      int y2 = (new Random()).nextInt(40);
		      g.drawLine(x1, y1, x2, y2);
		    } 
		  }
		  
		  private void getBorder(Graphics g) {
		    g.setColor(Color.BLACK);
		    g.drawRect(1, 1, 118, 38);
		  }
		  
		  private void getBackgroundColor(Graphics g) {
		    g.setColor(Color.WHITE);
		    g.fillRect(0, 0, 120, 40);
		  }
		  
	  
	  
}
